package com.villaday.idf.fragment;


import android.content.Intent;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.LinearLayout;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.villaday.idf.R;
import com.villaday.idf.activity.CreatOrderActivity;
import com.villaday.idf.activity.GoodsAndFodderActivityFor3;
import com.villaday.idf.adapter.HomeListSaleAdapter;
import com.villaday.idf.adapter.HomeListSaleHeadAdapter;
import com.villaday.idf.base.AbsRecyclerViewAdapter;
import com.villaday.idf.base.BaseFragment;
import com.villaday.idf.base.OnAdapterCallbackListener;
import com.villaday.idf.custom.DividerGridItem;
import com.villaday.idf.custom.LoadingDialog;
import com.villaday.idf.custom.DividerItemDecoration.RVItemDecoration;
import com.villaday.idf.model.PresellEntity;
import com.villaday.idf.util.Constant;
import com.villaday.idf.util.LogeUtil;
import com.villaday.idf.util.OkHttpUtil;
import com.villaday.idf.util.PhoneUtil;
import com.villaday.idf.util.ToastUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.Unbinder;

/**
 * 特卖
 */
public class HomeListSaleFragment extends BaseFragment implements OkHttpUtil.OnDataListener, View.OnClickListener, OnAdapterCallbackListener, AbsRecyclerViewAdapter.OnItemClickListener, SwipeRefreshLayout.OnRefreshListener {

    @BindView(R.id.rv)
    RecyclerView rv;

    @BindView(R.id.srl)
    SwipeRefreshLayout srl;
    Unbinder unbinder;
    private LoadingDialog loadingDialog;
    private Gson gson = new GsonBuilder().create();
    private HomeListSaleAdapter homeListSaleAdapter;
    List<PresellEntity.BodyEntity.PresellListEntity.ListEntity> data = new ArrayList();
    List<PresellEntity.BodyEntity.RecomendListEntity.ListEntityX> dataHead = new ArrayList();

    private int pageNo = 1;
    private int nextIndex = 1;
    private int pageSize = 10;
    private HomeListSaleHeadAdapter homeListSaleHeadAdapter;
    private ErrorLayout errorLayout;


    public static HomeListSaleFragment newInstance() {
        HomeListSaleFragment fragment = new HomeListSaleFragment();
        return fragment;
    }


    @Override
    protected int getViewResId() {
        return R.layout.fragment_home_list_sale;
    }

    @Override
    protected void init(View v) {
        srl.setOnRefreshListener(this);
        loadingDialog = LoadingDialog.newInstance("加载中");
        loadingDialog.show(getActivity().getFragmentManager(), "loading");
        rv.setLayoutManager(new LinearLayoutManager(getContext()));
        homeListSaleAdapter = new HomeListSaleAdapter(getContext(), this, this);
        rv.setAdapter(homeListSaleAdapter);

        rv.addItemDecoration(new RVItemDecoration(LinearLayout.VERTICAL, PhoneUtil.dp2px(getContext(), 7), getResources().getColor(R.color.colorBg), PhoneUtil.dp2px(getContext(), 8)));
        homeListSaleAdapter.setOnItemClickListener(this);
       /* View inflate = View.inflate(getContext(), R.layout.recycle_head, null);
        homeListSaleAdapter.addHeaderView(inflate);*/
        homeListSaleAdapter.setEmptyView(R.layout.empty_tips);
        homeListSaleAdapter.setEmptyTips(R.id.tv_emptyTips, "没有更多了");


        //initHead(inflate);
        //添加删除线
        //tvDelete.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
    }

    private void initHead(View inflate) {
        RecyclerView rvHead = (RecyclerView) inflate.findViewById(R.id.rv_head);

        rvHead.setLayoutManager(new LinearLayoutManager(getContext()));
        homeListSaleHeadAdapter = new HomeListSaleHeadAdapter(getContext(), this, this);
        rvHead.setAdapter(homeListSaleHeadAdapter);
        rvHead.addItemDecoration(new DividerGridItem(getContext()));
        homeListSaleHeadAdapter.setOnItemClickListener(this);
    }

    @Override
    protected void loadData() {
        getData();
    }

    private void getData() {
        Map<String, String> map = new HashMap<>();
        map.put("pageNo", pageNo + "");
        map.put("pageSize", pageSize + "");
        OkHttpUtil.getJSON(getContext(), Constant.URL.presell, map, this);
    }

    @Override
    public void onResponse(String url, String json) {
        if (errorLayout != null) {

            errorLayout.setSuccess();
        }
        dismissLoading();
        if (!TextUtils.isEmpty(json)) {

            if (Constant.URL.presell.equals(url)) {
                LogeUtil.e("presell", json);

                PresellEntity presellEntity = gson.fromJson(json, PresellEntity.class);
                removeLoadingItem();
                if (pageNo == 1) {
                    data.clear();
                }
                dismissLoading();
                if ("200".equals(presellEntity.getCode())) {
                   /* if (pageNo == 1 && presellEntity.getBody().getRecomendList() != null && presellEntity.getBody().getRecomendList().getList() != null) {

                        dataHead.addAll(presellEntity.getBody().getRecomendList().getList());
                        homeListSaleHeadAdapter.setData(dataHead);
                    }*/
                    data.addAll(presellEntity.getBody().getPresellList().getList());
                    if (presellEntity.getBody().getPresellList().isHasNext()) {
                        data.add(new PresellEntity.BodyEntity.PresellListEntity.ListEntity(1));
                        nextIndex = pageNo + 1;

                    } else {
                        addBaseLine();
                    }

                } else {
                    addBaseLine();
                }
                homeListSaleAdapter.setData(data);

            }
        }


    }


    @Override
    public void onFailure(String url, String error) {
        dismissLoading();
        if (Constant.URL.presell.equals(url)) {
            if (errorLayout != null) {

                errorLayout.setError(1);
            }
            ToastUtil.initToast(getContext(),"网络错误");

        }
    }

    private void removeLoadingItem() {
        if (data.size() > 0) {
            if (data.get(data.size() - 1).getMyType() == 1) {
                data.remove(data.size() - 1);
            }
        }
    }

    private void addBaseLine() {
        if (pageNo != 1) {
            data.add(new PresellEntity.BodyEntity.PresellListEntity.ListEntity(2));
        }
    }

    private void dismissLoading() {
        if (loadingDialog != null) {
            loadingDialog.dismiss();
        }
        if (srl != null && srl.isRefreshing()) {
            srl.setRefreshing(false);
        }

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_tuiguang:
                Intent intent = new Intent(getContext(), GoodsAndFodderActivityFor3.class);
                intent.putExtra("type", 1);
                intent.putExtra("persellId", data.get((Integer) view.getTag()).getId());
                intent.putExtra("houseId", data.get((Integer) view.getTag()).getHouse().getId());
                intent.putExtra("brokerAge", data.get((Integer) view.getTag()).getBrokerAge());

                startActivity(intent);
                break;

            case R.id.tv_lijiBuy:
                Intent intent3 = new Intent(getContext(), CreatOrderActivity.class);
                intent3.putExtra("type", 7);
                intent3.putExtra("activity_id", data.get((Integer) view.getTag()).getId());
                intent3.putExtra("activity_type", 13);
                intent3.putExtra("hasHouse", data.get((Integer) view.getTag()).isHasHouse());

                startActivity(intent3);
                break;
        }
    }

    @Override
    public void onCallback() {
        if (nextIndex == pageNo + 1) {
            pageNo++;
            getData();
        }

    }

    @Override
    public void onItemClick(View v, int position) {
        Intent intent = new Intent(getContext(), GoodsAndFodderActivityFor3.class);
        intent.putExtra("houseId", data.get(position).getHouse().getId());
        intent.putExtra("brokerAge", data.get(position).getBrokerAge());
        intent.putExtra("persellId", data.get(position).getId());
        startActivity(intent);
    }


    @Override
    public void onRefresh() {
        pageNo = 1;
        nextIndex = 1;
        getData();
    }

    public void setErrorLayout(ErrorLayout errorLayout) {

        this.errorLayout = errorLayout;
    }
}
